﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using RFW.Silverlight.Weather;

namespace RedfieldMobile
{
	public partial class MainPage : PhoneApplicationPage
	{
		private CurrentConditions _weatherData = null;
		private int _updateEvery = 1;
		private DateTime _lastLoaded = new DateTime(0);

		// Constructor
		public MainPage()
		{
			InitializeComponent();
		}

		private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
		{
			GetWeather();

			CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
		}

		void CompositionTarget_Rendering(object sender, EventArgs e)
		{
			TimeSpan ts = DateTime.Now - _lastLoaded;

			if (ts.TotalMinutes >= _updateEvery)
				GetWeather();
		}

		private void GetWeather()
		{
			pbLoading.Visibility = System.Windows.Visibility.Visible;

			if (_weatherData == null)
			{
				_weatherData = new PWS();
				_weatherData.DownloadComplete += new EventHandler(_weatherData_DownloadComplete);
				_weatherData.DownloadFailed += new EventHandler(_weatherData_DownloadFailed);
			}

			_weatherData.Get();
			_lastLoaded = DateTime.Now;
		}

		void _weatherData_DownloadFailed(object sender, EventArgs e)
		{
			pbLoading.Visibility = System.Windows.Visibility.Collapsed;
		}

		void _weatherData_DownloadComplete(object sender, EventArgs e)
		{
			wcWind.Direction = _weatherData.Wind.Direction;
			wcWind.Speed = _weatherData.Wind.Speed;

			ddTemp.Value = _weatherData.Temperature.F;
			ddHumidity.Value = _weatherData.Temperature.Humidity;
			ddPressure.Value = _weatherData.Pressure.IN;

			pbLoading.Visibility = System.Windows.Visibility.Collapsed;
		}
	}
}
